package com.ruoyi.model.service.impl;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.model.domain.DbInfo;
import com.ruoyi.model.mapper.DbInfoMapper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class DBPool {

    private DBPool() {
    }

    private static DBPool instance = new DBPool();

    private Map<Long,HikariDataSource> map = new ConcurrentHashMap<Long,HikariDataSource>();

    public static DBPool getInstance() {
        return instance ;
    }

    public synchronized HikariDataSource getDBPool(Long dbId) {
        HikariDataSource hikariDataSource = map.get(dbId);
        if(Objects.isNull(hikariDataSource)) {
            DbInfoMapper dbInfoMapper = SpringUtils.getBean(DbInfoMapper.class);
            DbInfo dbInfo = dbInfoMapper.selectDbInfoByDbId(dbId);
            HikariConfig config = new HikariConfig();
            HikariDataSource ds;
            config.setDriverClassName("com.mysql.cj.jdbc.Driver");
            config.setJdbcUrl(dbInfo.getDbUrl());
            config.setUsername(dbInfo.getUserName());
            config.setPassword(dbInfo.getUserPass());
            config.setSchema(dbInfo.getDefaultSchema());
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            config.setKeepaliveTime(600000l);
            config.setPoolName("Mysql-sync-pool-" + dbId);
            config.setMinimumIdle(3);
            config.setMaximumPoolSize(20);
            config.addDataSourceProperty("logWriter", new PrintWriter(System.out));
            ds = new HikariDataSource(config);
            map.put(dbId, ds);
            return ds;
        } else {
            return hikariDataSource ;
        }
    }

}
